import { Col, Icon, message, Row, Spin } from 'antd';
import { Button, List, Radio } from 'antd-mobile';
import { addon, log } from "pao-aop";
import { reactControl, ReactView, ReactViewControl, ReactViewState } from "pao-aop-client";
import React from "react";
import { AppServiceUtility } from "src/projects/app/appService";
import { IntelligentElderlyCareAppStorage } from "src/projects/app/appStorage";
import { decodeUrlParam, encodeUrlParam, PAGE_TYPE, ROUTE_PATH } from "src/projects/app/util-tool";
import { isArray } from "util";
import './index.less';
const RadioItem = Radio.RadioItem;
/** 定时查询付款状态 */
let PAY_INTERVAL: any = undefined;
/** 财务模块是否被调用过 */
let MOMEY_CALL = false;
/**
 * 组件：重新支付状态
 */
export interface RepayViewState extends ReactViewState {
    pay_type?: any;
    value?: any;
    price?: any;
    /** 购买产品列表json信息字符串 */
    buy_list_json_str?: string;
    /** 请求支付信息接口返回的信息 */
    pay_mount_result?: any;
    /** 支付类型 */
    page_type?: string;
    /** 是否正在查询是否付款 */
    if_pay?: boolean;
}

/**
 * 组件：重新支付
 * 描述
 */
export class RepayView extends ReactView<RepayViewControl, RepayViewState> {
    constructor(props: any) {
        super(props);
        this.state = {
            pay_type: [
                // { value: 0, label: '银行卡支付', extra: 'money-collect' },
                { value: '微信支付', label: '微信支付', extra: 'wechat', disabled: false },
                { value: '支付宝支付', label: '支付宝支付', extra: 'alipay-circle', disabled: false },
                // { value: 3, label: '预存支付', extra: 'pay-circle' },
                // { value: 4, label: '扫脸支付', extra: 'smile' }
            ],
            value: '微信支付',
            price: 0,
            if_pay: false,
        };
    }

    checkIfPay = () => {
        let buy_list_json_str_b64 = this.props.match!.params.key;
        let buy_list_json = JSON.parse(decodeUrlParam(buy_list_json_str_b64));
        const user = IntelligentElderlyCareAppStorage.getCurrentUser();

        AppServiceUtility.service_order_service.third_trade_query!({
            'out_trade_no': buy_list_json['out_trade_no']
        })!.then((data: any) => {
            if (data.length === 0) {
                clearInterval(PAY_INTERVAL);
            } else if (data.length > 0) {
                // 已经付款，但是交易表查询结果未必是付款
                this.setState({
                    if_pay: true
                });
                // TODO: 未付款流程未处理
                if (data[0]['pay_status'] === '已付款') {
                    clearInterval(PAY_INTERVAL);
                    let total_fee = 0;
                    if (isArray(buy_list_json['page_info'])) {
                        buy_list_json['page_info'].map((e: any, i: number) => {
                            total_fee += e['amount_total'];
                        });
                    } else {
                        total_fee = buy_list_json['page_info'];
                    }

                    const payment_info = {
                        /** 支付类型 */
                        type: this.state.value,
                        /** 金额 */
                        amount: total_fee
                    };
                    // 调用财务模块接口
                    if (!MOMEY_CALL) {
                        MOMEY_CALL = true;
                        AppServiceUtility.app_pay_service.confirm_pay!(
                            '微信支付',
                            (() => {
                                if (buy_list_json['page_type'] === PAGE_TYPE.BUY) {
                                    return {
                                        payer_id: user.id,
                                        info: buy_list_json.page_info
                                    };
                                }
                                if (buy_list_json['page_type'] === PAGE_TYPE.CHARGE || buy_list_json['page_type'] === PAGE_TYPE.DONATION) {
                                    return {
                                        payer_id: user.id,
                                        info: this.getRealPay(),
                                        remarks: buy_list_json['remarks'],
                                        abstract: buy_list_json['abstract']
                                    };
                                }
                                return {};
                            })()
                        )!.then((data) => {
                            // if(data==='')
                            AppServiceUtility.comfirm_order_service.change_trade_status!(
                                buy_list_json.page_info[0].id,
                                '已付款'
                            );
                            log('财务模块接口调用', JSON.stringify(data));
                        });
                    }

                    this.props.history!.push(ROUTE_PATH.paymentSucceed + '/' + encodeUrlParam(JSON.stringify(payment_info)));
                } else {
                    this.setState({
                        if_pay: false
                    });
                    clearInterval(PAY_INTERVAL);

                }
            }
        });
    }

    componentDidMount() {
        let buy_list_json_str_b64 = this.props.match!.params.key;
        let buy_list_json = JSON.parse(decodeUrlParam(buy_list_json_str_b64));

        const user = IntelligentElderlyCareAppStorage.getCurrentUser();
        // 判断该单是否支付成功
        PAY_INTERVAL = setInterval(
            this.checkIfPay,
            1 * 1000
        );

        if (buy_list_json.page_type === PAGE_TYPE.BUY) {
            AppServiceUtility.app_pay_service.receive_pay_info!(
                {
                    payer_id: user.id,
                    info: buy_list_json.page_info
                }
            )!.then((data: any) => {
                this.setState(
                    {
                        page_type: PAGE_TYPE.BUY,
                        pay_mount_result: data,
                    },
                    () => {
                        const amount = this.getRealPay();
                        if (amount <= 0) {
                            this.setState({
                                pay_type: this.state.pay_type.map((e: any, i: number) => {
                                    e.disabled = true;
                                    return e;
                                })
                            });
                        }
                    });
            });
        }
    }

    getRealPay = () => {
        if (this.state.page_type === PAGE_TYPE.BUY) {
            return this.state.pay_mount_result['real']['amount'];
        }
    }

    goResult = () => {
        let buy_list_json_str_b64 = this.props.match!.params.key;
        let buy_list_json = JSON.parse(decodeUrlParam(buy_list_json_str_b64));
        const user = IntelligentElderlyCareAppStorage.getCurrentUser();

        const amount = this.getRealPay();

        if (amount <= 0) {
            // 不调用第三方支付接口
            log('支付模块', '不调用第三方接口');
            AppServiceUtility.app_pay_service.confirm_pay!(
                undefined,
                {
                    payer_id: user.id,
                    info: buy_list_json.page_info
                }
            )!.then((data) => {
                if (data === true) {
                    const payment_info = {
                        /** 支付类型 */
                        type: this.state.value,
                        /** 金额 */
                        amount: this.getRealPay()
                    };
                    this.props.history!.push(ROUTE_PATH.paymentSucceed + '/' + encodeUrlParam(JSON.stringify(payment_info)));
                } else {
                    message.error('支付失败！');
                }
            });
        } else {
            // 调用第三方支付
            log('支付模块', '调用第三方接口');
            if (this.state.value === '微信支付') {
                log('支付模块', '微信支付');
                let sendJson = {
                    page_title: document.title,
                    product_desc: buy_list_json['product_desc'],
                    // total_fee: this.getRealPay(),
                    total_fee: this.getRealPay(),
                    out_trade_no: buy_list_json['out_trade_no'],
                };
                if ((buy_list_json as Object).hasOwnProperty("attach")) {
                    sendJson['attach'] = buy_list_json['attach'];
                }
                AppServiceUtility.my_order_service.wechat_payment!(
                    sendJson
                )!.then((data: any) => {
                    window.location.href = data.mweb_url;
                });
            }
            if (this.state.value === '支付宝支付') {
                log('支付模块', '支付宝支付');
                AppServiceUtility.app_pay_service.alipay!(

                )!.then(data => {

                });
            }
        }
    }

    radioChange = (value: any) => {
        this.setState({
            value
        });
    }

    render() {
        const { value } = this.state;
        let ele = <></>;
        console.warn(this.state.pay_mount_result);

        if (this.state.pay_mount_result) {
            ele = (
                <div className="main-content">
                    <List renderHeader={'请选择一下支付方式'}>
                        {this.state.pay_type.map((item: any, i: number) => {
                            return (<RadioItem key={item.value} checked={value === item.value} disabled={item.disabled} onChange={() => this.radioChange(item.value)}><Icon type={item.extra} />&nbsp;&nbsp;{item.label}</RadioItem>);
                        })}
                    </List>
                    <div className="submit-btn">

                        <Row>
                            <Col span={12}>
                                <Button className={"btn-amount"} style={{ pointerEvents: "none" }}  >
                                    {'￥' + this.getRealPay()}
                                </Button>
                            </Col>
                            <Col span={12}>
                                <Button type="primary" onClick={this.goResult}>确认支付</Button>
                            </Col>
                        </Row>
                    </div>
                </div>
            );
        }

        return this.state.if_pay ?
            (
                <Spin spinning={true} tip={'支付结果查询中...'}>
                    {ele}
                </Spin>
            )
            :
            ele;
    }
}

/**
 * 控件：重新支付控制器
 * 描述
 */
@addon('RepayView', '重新支付', '描述')
@reactControl(RepayView, true)
export class RepayViewControl extends ReactViewControl {
    constructor() {
        super();
    }
}